<template>
  <main-card-admin title="系统日志" :tabs="getTabs()" :loading="loading" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button v-auth="'sys-log-login-export'" type="primary" @click="exportLog">导出</a-button>
    </template>
    <template #screen-space>
      <a-row :align="'middle'" justify="space-between">
        <a-col class="mr-24">
          <a-range-picker v-model:value="rangeValue" :show-time="{ format: 'HH:mm' }" format="YYYY-MM-DD HH:mm" @change="onRangeChange" />
        </a-col>
        <a-col flex="1" />
        <a-col>
          <condition-input :condition="condition" @search="onSearch" />
        </a-col>
      </a-row>
    </template>
    <template v-if="isTableRender">
      <a-table
        :style="{ width: '100%' }"
        :columns="tableColumns"
        class="admin-table"
        :data-source="logList"
        :pagination="false"
        @change="onTableChange"
      />
      <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getLogListData" />
    </template>
  </main-card-admin>
</template>

<script lang="ts" setup>
  import dayjs from 'dayjs'
  import { dateFormat } from 'g6-fn'
  import { nextTick, ref } from 'vue'

  import ConditionInput, { SearchFn } from '@/components/ConditionInput/index.vue'
  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import useList from '@/hooks/use-list'
  import { logApi } from '@/services/api'
  import { waitLoading } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'

  import { getTabs } from '../utils'

  interface PageForm {
    username: string
    ip: string
    startTime: string
    endTime: string
    columns: 'operationTime'
    order: 'desc' | 'asc'
  }
  const condition = [
    { name: 'IP', key: 'ip' },
    { name: '用户名称', key: 'username' }
  ]

  const onSearch = (obj: SearchFn) => {
    console.log('obj:', obj)
    getLogListData({ offset: 1, ...obj })
  }
  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '用户名称',
        dataIndex: 'username',
        minWidth: 120
      },
      {
        title: 'IP',
        dataIndex: 'ip',
        minWidth: 120
      },
      {
        title: 'IP归属地',
        dataIndex: 'ipHome',
        minWidth: 140
      },
      {
        title: '操作系统',
        dataIndex: 'os',
        width: 140
      },
      {
        title: '浏览器',
        dataIndex: 'browser',
        width: 140
      },
      {
        title: '时间',
        dataIndex: 'operationTime',
        isSort: true,
        width: 200
      },
      {
        title: '登录方式',
        dataIndex: 'operation',
        width: 160
      }
    ])
  )

  const THREE_DAY = 3 * 24 * 60 * 60 * 1000 // 三天的毫秒数
  const rangeValue = ref<any>([dayjs(Date.now() - THREE_DAY), dayjs(Date.now())])

  const {
    pageForm,
    dataList: logList,
    getDataList: getLogListData,
    resetPageForm,
    previousPageForm,
    loading
  } = useList<PageForm, any>(logApi.loginLog, {
    username: '',
    ip: '',
    startTime: dateFormat(rangeValue.value[0], 'YYYY-MM-DD HH:mm:ss'),
    endTime: dateFormat(rangeValue.value[1], 'YYYY-MM-DD HH:mm:ss'),
    columns: 'operationTime',
    order: 'desc'
  })

  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    const order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getLogListData({ offset: 1, order })
  }

  const onRangeChange = (e: any) => {
    let startTime = ''
    let endTime = ''
    if (e) {
      startTime = dateFormat(e[0], 'YYYY-MM-DD HH:mm:ss')
      endTime = dateFormat(e[1], 'YYYY-MM-DD HH:mm:ss')
    }
    getLogListData({ startTime, endTime })
  }

  const isTableRender = ref(true)
  const refreshTable = async () => {
    isTableRender.value = false
    await nextTick()
    isTableRender.value = true
  }

  const reset = () => {
    rangeValue.value = [dayjs(Date.now() - THREE_DAY), dayjs(Date.now())]
    let startTime = dateFormat(rangeValue.value[0], 'YYYY-MM-DD HH:mm:ss')
    let endTime = dateFormat(rangeValue.value[1], 'YYYY-MM-DD HH:mm:ss')
    // console.log(pageForm, 'pageForm')
    resetPageForm({ startTime, endTime })
    refreshTable()
  }

  const exportLog = () => {
    waitLoading(
      logApi.exportLoginLog(
        previousPageForm.value,
        {
          isResponseAll: true,
          headers: {
            'Export-Key': 'login_log_export'
          }
        },
        '登录日志.xlsx'
      )
    )
  }

  getLogListData()
</script>
